package com.ruoyi.system.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thingsboard.rest.client.RestClient;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.security.Authority;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.system.service.IThingsBoardService;

@Service
public class ThingsBoardServiceImpl implements IThingsBoardService {
	
	@Value("${tb.url}")
	private String url;
	
	@Value("${tb.sysadminUsername}")
	private String adminUsername;
	
	@Value("${tb.sysadminPassword}")
	private String adminPassword;

	@Override
	public Tenant addNewTenant(String tenantTitle) {
		
		Tenant tenant = new Tenant();
		tenant.setTitle(tenantTitle);
		
		try(RestClient client = new RestClient(url)){
			client.login(adminUsername, adminPassword);
			tenant = client.saveTenant(tenant);
		}
		
		return tenant;
	}

	@Override
	public User addNewTenantUser(Tenant tenant, String userEmail, String userPassword) {
		User tenantUser = new User();
		tenantUser.setAuthority(Authority.TENANT_ADMIN);
		tenantUser.setEmail(userEmail);
		tenantUser.setTenantId(tenant.getId());
		
		try(RestClient client = new RestClient(url)){
			client.login(adminUsername, adminPassword);
			tenantUser = client.saveUser(tenantUser, false);
			client.activateUser(tenantUser.getId(), userPassword,false);
		}
		
		return tenantUser;
	}

	@Override
	public String checkTenantTitleUnique(String tenantTitle) {
		
		//TODO 新增公司在创建thingsboard租户时，可能在创建租户用户时发生回滚，但此时thingsboard上的租户可能已生成，所以需要在下次创建租户时检查是否租户名称已创建
		return UserConstants.NOT_UNIQUE;
	}
}
